//
//  NumberPadCollectionLayout.swift
//  E-CycleForShop
//
//  Created by enghou on 17/4/21.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit

class NumberPadCollectionLayout: UICollectionViewLayout {
    override var collectionViewContentSize: CGSize{
        get{
            guard self.collectionView != nil else {
                return CGSize.zero
            }
            let height = self.collectionView!.frame.size.height * CGFloat(self.collectionView!.numberOfItems(inSection: 0))
            let width = self.collectionView!.frame.size.width
            return CGSize.init(width: width, height: height)
        }
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attributes = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
        let collection = self.collectionView!
        let height = collection.frame.size.height
        let y = collection.contentOffset.y
        attributes.size = collection.frame.size
        attributes.center = CGPoint.init(x: collection.frame.size.width / CGFloat(2.0), y: height / CGFloat(2.0) + CGFloat(indexPath.row) * height)
        var transform = CATransform3DIdentity
        //初始的角度加上随contentoffset变化的角度
        let angle = CGFloat(indexPath.row) *  CGFloat(Double.pi) / 5 - 2.0 * CGFloat(Double.pi) * y / collection.contentSize.height
        transform = CATransform3DRotate(transform, angle, 1, 0, 0)
        attributes.transform3D = transform
        return attributes
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        if let array = super.layoutAttributesForElements(in: rect) {
            if array.count > 0 {
                return array
            }
        }
        var attributes : Array<UICollectionViewLayoutAttributes> = []
        for i in 0 ..< self.collectionView!.numberOfItems(inSection: 0) {
            let index = IndexPath.init(item: i, section: 0)
            if let att = self.layoutAttributesForItem(at: index) {
                attributes.append(att)
            }
        }
        return attributes
    }
    
}
